//
//  SearchHistoryController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/24.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "SearchHistoryController.h"
#define kleftSpace 10
#define keywordCount 7
//unitls
#import "UIColor+Hex.h"
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
//views
#import "TopicHotkeyView.h"
#import "MTA.h"
@interface SearchHistoryController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic, strong) TopicHotkeyView *topicHotkeyView;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *keywordsArr;
@property(nonatomic, strong)NSMutableArray *historyListArr;
@property(nonatomic, strong)UIButton *bottomView;

@end

@implementation SearchHistoryController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _historyListArr = [[NSMutableArray alloc]init];
    _keywordsArr = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    [self setupSubView];
    [self loadHotKeywordData];
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.historyListArr removeAllObjects];
    [self.historyListArr addObjectsFromArray:[self historyDataFromUserdefault]];
    if (self.historyListArr.count == 0) {
        [self.bottomView setTitle:@"暂无搜索历史" forState:UIControlStateNormal];
        self.bottomView.enabled = NO;
    } else {
        [self.bottomView setTitle:@"清空搜索历史" forState:UIControlStateNormal];
        self.bottomView.enabled = YES;
    }
    
    [self.tableView reloadData];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"搜索历史"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"搜索历史"];
}
#pragma mark -- request data
- (void)loadHotKeywordData {
    //请求参数说明： SIGNATURE  设备识别码
    //      STOREID     商品ID
    //      SIZE         要获取的关键字数量
    XiaoQuAndStoreInfoModel *mode = [[ManagerGlobeUntil sharedManager] getxiaoQuAndStoreInfo];
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:[NSString stringISNull:mode.storeID] forKey:@"STOREID"];
    [parameter setObject:[NSNumber numberWithInteger:keywordCount] forKey:@"SIZE"];
    __weak typeof(self)weakSelf = self;
    [manager parameters:parameter customPOST:@"search/keywords" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *msg = [dataDic objectForKey:@"MSG"];
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            [self.keywordsArr removeAllObjects];
            if ([state isEqualToString:@"0"]) {//请求成功
                [weakSelf.keywordsArr addObjectsFromArray:[dataDic objectForKey:@"OBJECT"]];
                [weakSelf.topicHotkeyView setHotkeys:[weakSelf.keywordsArr copy]];
            }else {//请求失败
                [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
            }
        }
        
        
    } failure:^(bool isFailure) {
        
        
    }];
}

#pragma makr -- 初始化视图
- (void)setupSubView {
    //头部视图
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectZero];
    headerView.backgroundColor = [UIColor colorWithHexString:@"ffffff"];
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(kleftSpace
                                                                  , 0
                                                                  , CGRectGetWidth(self.view.bounds) - 2*kleftSpace
                                                                   , 39)];
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
    titleLabel.text = @"热门搜索";
    [headerView addSubview:titleLabel];
    
    _topicHotkeyView = [[TopicHotkeyView alloc]initWithFrame:CGRectMake(0, 40, CGRectGetWidth(self.view.bounds), 0)];
    //点击事件
    _topicHotkeyView.block = ^(NSDictionary *dict) {
         [[NSNotificationCenter defaultCenter] postNotificationName:ksearchHistory object:nil userInfo:@{ksearchKeyWord:[NSString stringTransformObject:[dict objectForKey:@"KEYWORD"]],ksearchKeyWordId:[NSString stringTransformObject:[dict objectForKey:@"ID"]] }];
    };
    [headerView addSubview:_topicHotkeyView];
    headerView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 40 + 85);
    //底部视图
    _bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), HightScalar(50));
    [_bottomView addTarget:self action:@selector(clearHistoryDataEvent) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView setTitleColor:[UIColor colorWithHexString:@"#707070"] forState:UIControlStateNormal];
    [_bottomView.layer setBorderWidth:0.7];
    [_bottomView.layer setBorderColor:[UIColor colorWithHexString:@"#dddddd"].CGColor];
    _bottomView.titleLabel.font = [UIFont systemFontOfSize:FontSize(18)];
    
    //初始化table
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 65)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableHeaderView = headerView;
    _tableView.tableFooterView = _bottomView;
    [self.view addSubview:_tableView];
    
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.historyListArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.imageView.image=[UIImage imageNamed:@"search_icon_seahistory"];
    cell.textLabel.text = [self.historyListArr objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor colorWithHexString:@"#707070"];
    cell.textLabel.font = [UIFont systemFontOfSize:FontSize(16)];
    return cell;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return HightScalar(50);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *keyword = [self.historyListArr objectAtIndex:indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:ksearchHistory object:nil userInfo:@{ksearchKeyWord:keyword,ksearchKeyWordId:@""}];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self hideKeyboard];
}
#pragma mark -- button Action
- (void)clearHistoryDataEvent {
    [self removeAllObject];
    [self.historyListArr removeAllObjects];
    [self.bottomView setTitle:@"暂无搜索历史" forState:UIControlStateNormal];
    self.bottomView.enabled = NO;
    [self.tableView reloadData];
}
#pragma mark -- 对历史数据进行处理
//获取历史查询信息
-(NSArray*)historyDataFromUserdefault
{
    NSArray * historyArr = [[NSUserDefaults standardUserDefaults] objectForKey:ksearchHistory];
    return historyArr;
}

- (void)removeAllObject
{
    NSArray * array = [[NSArray alloc]init];
    [[NSUserDefaults standardUserDefaults] setObject:array forKey:ksearchHistory];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark -- 隐藏键盘
- (void)hideKeyboard {
    [[NSNotificationCenter defaultCenter] postNotificationName:khideSearchKeyboard object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
